package com.ag.improvedjava.iterable;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SingleElementIterable<T> implements Iterable<T> {

	private T element;
	
	SingleElementIterable(T defaultElement) {
		this.element = defaultElement;
	}

	@Override
	public Iterator<T> iterator() {
		return new SingleElementIterator<>(element);
	}
}

class SingleElementIterator<T> extends UnmodifiableIterator<T> {
	
	private T element;
	private boolean nextMethodCalled;
	
	SingleElementIterator(T element) {
		this.element = element;
	}

	@Override
	public boolean hasNext() {
		return !nextMethodCalled;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		nextMethodCalled = true;
		return element;
	}

}
